package com.ly.common.running.exception;

import com.ly.common.running.config.Context;
import jdk.nashorn.internal.runtime.regexp.joni.Config;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.helpers.MessageFormatter;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

@Slf4j
public class ExceptionCode {
    private static final String PATH = "classpath*:errcode/*.properties";
    static Map<String,String> errorCodeMap = new HashMap<>();

    static boolean init = false;

    private static void init(){
        log.info("第一次加载错误码");
        new ExceptionCode();
    }

    public ExceptionCode(){
        try {
            Resource[] resources = new PathMatchingResourcePatternResolver().getResources(PATH);
            for(Resource e:resources){
                Properties properties = new Properties();
                properties.load(e.getInputStream());
                for(Object var:properties.keySet()){
                    errorCodeMap.put(var.toString(),properties.getProperty(var.toString()));
                }
            }
        } catch (Exception e) {
            log.error("{}",e);
            throw new ConfigException("加载错误码异常",e);
        }
        init = true;
    }

    public static String getErrorMessage(String errorCode,Object... errorParams){
        if(init){
            new ExceptionCode();
        }
        String message = errorCodeMap.get(errorCode);
        if(message == null || message.equals("")){
            log.error("未找到错误码[{}]定义",errorCode);
        }
        return MessageFormatter.arrayFormat(message,errorParams).getMessage();
    }

    public static void pringExceptionByLog(Exception e){
        if(e instanceof BusinessException){
            if(log.isDebugEnabled()){
                log.debug("FLOW[{}] has exception[{}]", Context.get().getSysHead().getServiceNo(),e);
            }else {
                log.error("FLOW[{}] BusinessException details:[{}]",Context.get().getSysHead().getServiceNo(),e.getMessage());
            }
        }else {
            log.error("Exception details:[{}]",e);
        }
    }
}
